<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
include "common/common.php";

define('STATUS_OK', 200);
define('STATUS_AUTH', 401); //接口需要登录时,返回此状态码
define('STATUS_INVALD_PARAM', 402);
define('STATUS_NOT_FOUND', 404);
define('STATUS_FORBIDDEN', 405);

define('STATUS_FAIL', 400);

/**
 * 获取一个错误对应的默认消息
 *
 * @param integer $code
 * @return void
 */
function getDefaultMessage(int $code)
{
    switch ($code) {
        case STATUS_OK:
            return "成功";
        case STATUS_FAIL:
            return "未分类错误";
        case STATUS_AUTH:
            return "未登陆或Token已失效";
        case STATUS_INVALD_PARAM:
            return "参数有误";
        case STATUS_FORBIDDEN:
            return "没有权限执行此操作";
        default:
            return "未定义的错误";
    }
}

/**
 * 生成一个统一的json格式响应
 *
 * @param array $data
 * @param integer $status
 * @param [type] $errMsg
 * @return void
 */
function json_response(array $data, int $status = STATUS_OK, $errMsg = null)
{
    return Response::create(['data' => $data, 'status' => $status,'errmsg'=>$errMsg!==null?$errMsg:getDefaultMessage($status)], 'json');
}

/**
 * 打印统一的json格式响应,并结束脚本
 *
 * @param array $data
 * @param integer $status
 * @param [type] $errMsg
 * @return void
 */
function json_exit(array $data, int $status = STATUS_OK, $errMsg = null)
{
    $ret = json_response($data, $status, $errMsg);
    $ret->send();
    exit(0);
}
